package com.jtpay.payresulthelper.provider;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import com.google.gson.JsonObject;
import com.jtpay.payresulthelper.db.AliPayColumn;
import com.jtpay.payresulthelper.db.AliQueryOrderColumn;
import com.jtpay.payresulthelper.http.dataStructure.BasicResponse;
import com.jtpay.payresulthelper.model.AliDbModel;
import com.jtpay.payresulthelper.util.LogUtil;
import com.jtpay.payresulthelper.util.PayContext;
import com.jtpay.payresulthelper.util.SharedPreferenceUtil;
import com.jtpay.payresulthelper.util.manager.ExceptionUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jtpay.payresulthelper.constant.HooKConstant.*;
import static com.jtpay.payresulthelper.util.PayContext.ALI_ACCOUNT;

/**
 * Description:
 * File: AliDbDataProvider.java
 * Author: Administrator
 * Create: 2018/09/16 10:44
 */
public class AliDbDataProvider {
    private static Uri mUri = Uri.parse(CONTENT_URI);
    private static Uri mTaskUri = Uri.parse(CONTENT_TASK_URI);
    private static Uri mTempUri = Uri.parse(CONTENT_TEMP_URI);

    private static SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private static SimpleDateFormat taskDateFormat =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private static SharedPreferenceUtil sharedPreferenceUtil = new SharedPreferenceUtil();


    public static synchronized boolean isTaskNull(Context context) {
        Cursor c = null;
        try {
            c = context.getContentResolver().query(mTaskUri,
                    new String[]{AliQueryOrderColumn._ID},
                    AliPayColumn._IS_OK + "=? or "
                            + AliPayColumn._IS_OK + "=?",
                    new String[]{"0", "1"},
                    "_id DESC limit " +
                            String.valueOf(PayContext.OFFICE_LIMIT_NUM));

            if (c != null && c.moveToNext()) {
                return false;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo IllegalArgumentException = " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo Exception = " + e.getMessage());
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return true;
    }

    /**
     * @param context Context
     * @return EncryptModel
     */
    public static synchronized AliDbModel selectAliDbInfo(Context context) {
        Cursor c = null;
        String aliAccount = getAliAccount(context);
        try {
            c = context.getContentResolver().query(mUri,
                    new String[]{AliPayColumn._ID,
                            AliPayColumn._DATE,
                            AliPayColumn._MONEY,
                            AliPayColumn._REMARK,
                            AliPayColumn._IS_OK,
                            AliPayColumn._ORDER_NUMBER,
                            AliPayColumn._TIME_STAMP,
                    },
                    AliPayColumn._IS_OK + "=? and "
                            + AliPayColumn._REMARK + "!=? and "
                            + AliPayColumn._ACCOUNT + "=?",
                    new String[]{"0" + "", "", aliAccount},
                    "_id DESC limit " +
                            String.valueOf(PayContext.OFFICE_LIMIT_NUM));

            if (c != null && c.moveToNext()) {
                AliDbModel bean = new AliDbModel();
                bean.set_id(c.getLong(c.getColumnIndexOrThrow(AliPayColumn._ID)));
                bean.set_money(c.getString(c.getColumnIndexOrThrow(AliPayColumn._MONEY)));
                bean.set_remark(c.getString(c.getColumnIndexOrThrow(AliPayColumn._REMARK)));
                bean.set_is_ok(c.getString(c.getColumnIndexOrThrow(AliPayColumn._IS_OK)));
                bean.set_date(c.getString(c.getColumnIndexOrThrow(AliPayColumn._DATE)));
                bean.set_order_number(c.getString(c.getColumnIndexOrThrow(AliPayColumn._ORDER_NUMBER)));
                bean.set_time_stamp(c.getString(c.getColumnIndexOrThrow(AliPayColumn._TIME_STAMP)));
                LogUtil.log("selectAliDbInfo " + bean.toString());

                update(bean.get_id(), "1", context);

                return bean;

            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo IllegalArgumentException = " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo Exception = " + e.getMessage());
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    /**
     * @param context Context
     * @return EncryptModel
     */
    public static synchronized AliDbModel selectAliSupplementInfo(Context context) {
        Cursor c = null;
        try {
            c = context.getContentResolver().query(mTempUri,
                    new String[]{AliPayColumn._ID,
                            AliPayColumn._DATE,
                            AliPayColumn._MONEY,
                            AliPayColumn._REMARK,
                            AliPayColumn._IS_OK,
                            AliPayColumn._ORDER_NUMBER,
                            AliPayColumn._TIME_STAMP,
                    },
                    AliPayColumn._IS_OK + "=? and "
                            + AliPayColumn._REMARK + "!=?",
                    new String[]{"0" + "", ""},
                    "_id DESC limit " +
                            String.valueOf(PayContext.OFFICE_LIMIT_NUM));

            if (c != null && c.moveToNext()) {
                AliDbModel bean = new AliDbModel();
                bean.set_id(c.getLong(c.getColumnIndexOrThrow(AliPayColumn._ID)));
                bean.set_money(c.getString(c.getColumnIndexOrThrow(AliPayColumn._MONEY)));
                bean.set_remark(c.getString(c.getColumnIndexOrThrow(AliPayColumn._REMARK)));
                bean.set_is_ok(c.getString(c.getColumnIndexOrThrow(AliPayColumn._IS_OK)));
                bean.set_date(c.getString(c.getColumnIndexOrThrow(AliPayColumn._DATE)));
                bean.set_order_number(c.getString(c.getColumnIndexOrThrow(AliPayColumn._ORDER_NUMBER)));
                bean.set_time_stamp(c.getString(c.getColumnIndexOrThrow(AliPayColumn._TIME_STAMP)));
                LogUtil.log("selectAliSupplementInfo " + bean.toString());
                updateSupplement(bean.get_id(), "1", context);
                return bean;

            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo IllegalArgumentException = " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbInfo Exception = " + e.getMessage());
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    /**
     * @param context Context
     * @return EncryptModel
     */
    public static synchronized List<AliDbModel> selectAliDbErrorListInfo(Context context) {
        Cursor c = null;
        String aliAccount = getAliAccount(context);
        try {
            c = context.getContentResolver().query(mUri,
                    new String[]{AliPayColumn._ID,
                            AliPayColumn._DATE,
                            AliPayColumn._MONEY,
                            AliPayColumn._REMARK,
                            AliPayColumn._IS_OK,
                            AliPayColumn._ORDER_NUMBER,
                            AliPayColumn._TIME_STAMP,
                    },
                    AliPayColumn._IS_OK + "=? and "
                            + AliPayColumn._REMARK + "!=? and "
                            + AliPayColumn._ACCOUNT + "=?",
                    new String[]{"4" + "", "", aliAccount},
                    "_id DESC limit " +
                            String.valueOf(PayContext.OFFICE_NUM));

            List<AliDbModel> list = new ArrayList<>();
            while (c != null && c.moveToNext()) {
                AliDbModel bean = new AliDbModel();
                bean.set_id(c.getLong(c.getColumnIndexOrThrow(AliPayColumn._ID)));
                bean.set_money(c.getString(c.getColumnIndexOrThrow(AliPayColumn._MONEY)));
                bean.set_remark(c.getString(c.getColumnIndexOrThrow(AliPayColumn._REMARK)));
                bean.set_is_ok(c.getString(c.getColumnIndexOrThrow(AliPayColumn._IS_OK)));
                bean.set_date(c.getString(c.getColumnIndexOrThrow(AliPayColumn._DATE)));
                bean.set_order_number(c.getString(c.getColumnIndexOrThrow(AliPayColumn._ORDER_NUMBER)));
                bean.set_time_stamp(c.getString(c.getColumnIndexOrThrow(AliPayColumn._TIME_STAMP)));
                update(bean.get_id(), "1", context);
                list.add(bean);
            }
            LogUtil.log("selectAliDbErrorListInfo " + list.toString());
            return list;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbErrorListInfo IllegalArgumentException = " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ProviderHelper selectAliDbErrorListInfo Exception = " + e.getMessage());
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    /**
     * upload result provider data update db
     * update treated
     */
    public static synchronized void update(long id, String treated, Context context) {
        ContentValues values = new ContentValues();
        Uri updateIdUri = ContentUris.withAppendedId(
                mUri, id);
        values.put(AliPayColumn._IS_OK, treated);
        context.getContentResolver().update(updateIdUri, values, null, null);
    }

    /**
     * upload result provider data update db
     * update treated
     */
    public static synchronized void updateSupplement(long id, String treated, Context context) {
        ContentValues values = new ContentValues();
        Uri updateIdUri = ContentUris.withAppendedId(
                mTempUri, id);
        values.put(AliPayColumn._IS_OK, treated);
        context.getContentResolver().update(updateIdUri, values, null, null);
    }

    public static synchronized void insertTask(Context context, BasicResponse<JsonObject> response) {
        ContentValues contentValues = new ContentValues();
        try {
            Date startDate = taskDateFormat.parse(response.getBeginTime());
            Date endDate = taskDateFormat.parse(response.getEndTime());
            contentValues.put(AliQueryOrderColumn._TIME_STAMP_BEGIN, String.valueOf(startDate.getTime()));
            contentValues.put(AliQueryOrderColumn._TIME_STAMP_END, String.valueOf(endDate.getTime()));
            contentValues.put(AliQueryOrderColumn._REMARK, response.getReason());
            contentValues.put(AliQueryOrderColumn._ORDER_NUMBER, response.getSupplierOrderId());
            context.getContentResolver().insert(mTaskUri, contentValues);
        } catch (ParseException e) {
            LogUtil.log("insertTask data error : " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * deleteAliDb
     *
     * @param context Context
     */
    public static synchronized void deleteAliDb(Context context) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            contentResolver.delete(mUri, null, null);
            contentResolver.delete(mTaskUri, null, null);
            contentResolver.delete(mTempUri, null, null);
            LogUtil.log("deleteAliDb");
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.log("deleteAliDb error : " + e.toString());
        }
    }

    /**
     * delete out of date data
     *
     * @param context Context
     * @param count   * days ago need negative
     */
    public static synchronized void deleteAliDbTargetData(Context context, int count) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -count);
        String targetDay = simpleDateFormat.format(calendar.getTime());
        String aliAccount = getAliAccount(context);
        try {
            ContentResolver contentResolver = context.getContentResolver();
            contentResolver.delete(mUri,
                    AliPayColumn._IS_OK + "=? and "
                            + AliPayColumn._DATE + "<? and "
                            + AliPayColumn._ACCOUNT + "=?",
                    new String[]{"2" + "", targetDay, aliAccount});
            LogUtil.log("deleteAliDbTargetData days : " + count);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.log("deleteAliDbTargetData error : " + e.toString());
        }
    }

    public static String getAliAccount(Context context) {
        if (TextUtils.isEmpty(ALI_ACCOUNT)) {
            ALI_ACCOUNT = sharedPreferenceUtil.SP_READ(context,
                    PayContext.SP_KEY_ALI_ACCOUNT_NAME);
        }
        return ALI_ACCOUNT;
    }

}
